<template>
	<!-- 
		//不适合移植小程序和uniapp，目前适合h5使用，移植h5的时候defimg换掉
	 -->
	<view style="text-align: left;font-weight: normal;">
		<view @click="paintposter()">. . .</view>
		<!-- 遮罩 -->
		<view class="fixed" v-if="fixshow == 2" @click="fixshow = 0"></view>
		<view class="fixed" v-if="fixshow == 1" @click="fixshow = 0"></view>
		<!-- 海报 -->
		<view class="fixedimgbox" v-if="fixshow == 1" @click="fixshow = 0">
			<image class="fixedimg" :src="postimgshowSrc" alt="" @click.stop=" "/>
			<canvas canvas-id="postimg" id="postimg" :style="{width:canvaspageWidth+'px',height:canvaspageHeight+'px'}" style="visibility: hidden;"></canvas>
		</view>
		<!-- 底部弹出 -->
		<view class="fixedbox" :class="fixshow == 1?'':'hidden'">
			<view class="fixedbox" style="position: relative;">
				<view class="title">
					分享至
				</view>
				<view class="navsbox" @click="fixshow = 2">
					<image src="" alt=""/>
					分享微信
				</view>
				<view class="navsbox" @click="getpostimg">
					<image src="" alt=""/>
					保存海报
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data:() => ({
			fixshow:0,
			getpostersuccess:1,
			postimgshowSrc:'',
			canvaspageWidth:0,
			canvaspageHeight:0,
		}),
		props:['canvasobj','ifwxapp'/* 0为h5，1为小程序 */],
		methods:{
			paintposterbase:function(canvaswidth,canvasheight,arrs,fn){
				var _this = this
				var imagegroup = []
				var imagedom = []
				var imgnum = 0
				var defimg = require('../images/defaultimg.png')//默认图片
				//canvas生成图片api
				this.canvaspageWidth = canvaswidth
				this.canvaspageHeight = canvasheight
				var c = uni.createCanvasContext('postimg',this)
				var cansfn = {
					imagecs:(item) => {
						c.save()
						if(item.circle==1){
							function csv(cw,ch,cx,cy){
								var r = 0
								if (cw < 2 * item.circler) r = cw / item.circler_deg;
								if (ch < 2 * item.circler) r = ch / item.circler_deg;
								c.beginPath();
								c.moveTo(cx + r, cy);
								c.arcTo(cx + cw, cy, cx + cw, cy + ch, item.circler_topright?r:0);
								c.arcTo(cx + cw, cy + ch, cx, cy + ch, item.circler_bottomright?r:0);
								c.arcTo(cx, cy + ch, cx, cy, item.circler_bottomleft?r:0);
								c.arcTo(cx, cy, cx + cw, cy, item.circler_topleft?r:0);
								c.closePath();
								c.clip();								
							}
							if(item.rotate==1){
								c.translate(item.x + item.w/2,item.y + item.h/2)
								c.rotate(item.deg/57.4)
								csv(item.w,item.h,-item.w/2,-item.h/2)
								c.drawImage(item.imagedom,-item.w/2,-item.h/2,item.w,item.h)
							}else{
								csv(item.w,item.h,item.x,item.y)
								c.drawImage(item.imagedom,item.x,item.y,item.w,item.h)		
							}
						}else{
							if(item.rotate==1){
								c.translate(item.x + item.w/2,item.y + item.h/2)
								c.rotate(item.deg/57.4)
								c.drawImage(item.imagedom,-item.w/2,-item.h/2,item.w,item.h)
							}else{
								c.drawImage(item.imagedom,item.x,item.y,item.w,item.h)		
							}			
						}
						c.restore()
					},
					textcs:(item)=>{
						c.save()
						c.font = item.fontSize+'px sans-serif';//设置字体大小
						if(item.linechange){
							var allRow = Math.ceil(c.measureText(item.word).width / item.maxWidth);//实际总共能分多少行
							var count = allRow >= item.maxLine ? item.maxLine : allRow;//实际能分多少行与设置的最大显示行数比，谁小就用谁做循环次数
								
							var endPos = 0;//当前字符串的截断点
							for (var j = 0; j < count; j++) {
								var nowStr = item.word.slice(endPos);//当前剩余的字符串
								var rowWid = 0;//每一行当前宽度    
								if (c.measureText(nowStr).width > item.maxWidth) {//如果当前的字符串宽度大于最大宽度，然后开始截取
									for (var m = 0; m < nowStr.length; m++) {
										rowWid += c.measureText(nowStr[m]).width;//当前字符串总宽度
										if (rowWid > item.maxWidth) {                        
											if (j === item.maxLine - 1) { //如果是最后一行
												c.fillText(nowStr.slice(0, m - 1) + '...', item.x, item.y + (j + 1) * (item.fontSize + 13));    //(j+1)*(item.fontSize + 13)这是每一行的高度        
											} else {
												c.fillText(nowStr.slice(0, m), item.x, item.y + (j + 1) * (item.fontSize + 13));
											}
											endPos += m;//下次截断点
											break;
										}
									}
								} else {//如果当前的字符串宽度小于最大宽度就直接输出
									c.fillText(nowStr.slice(0), item.x, item.y + (j + 1) * (item.fontSize + 13));
								}
							}							
						}else{
							c.fillText(item.word, item.x, item.y);
						}
						c.restore()
					}
				}
				//重组图片数组
				for(var i in arrs){
					if(arrs[i].type == 'image'){
						let temp = arrs[i]
						temp.imagedom = ''
						imagegroup.push(temp)
					}					
				}
				var checkcandrow = function(){
					var m = 0
					for(var i in imagegroup){
						if(imagegroup[i].result == 0){
							m = 1
						}			
					}
					if(m == 1){
						console.log('获取资源错误，无法生成海报')
					}else{
						for(var i in imagegroup){
							cansfn.imagecs(imagegroup[i])//使用图片api
						}
						for(var i in arrs){
							if(arrs[i].type != 'image'){
								cansfn.textcs(arrs[i])//使用文字api
							}					
						}
						setTimeout(() => {
							c.draw(true,()=>{
								try{
									uni.canvasToTempFilePath({
									  x: 0,
									  y: 0,
									  width: canvaswidth,
									  height: canvasheight,
									  destWidth: 0,
									  destHeight: 0,
									  canvasId: 'postimg',
									  success: function(res) {
										fn(res.tempFilePath,1)//生成海报成功
									  },
									  fail:function(error){
										  console.log(error)
										  fn(defimg,0)
									  }
									},_this)
								}catch(e){
									fn(require('../images/errorimg.jpg'),0)	//生成海报失败
								}
							})
						},100)
					}
				}
				var errloadimg = function(item){
					imagegroup[imgnum].result = 1
					imagegroup[imgnum].imagedom = defimg
					imgnum = imgnum + 1
					loadimg(imagegroup[imgnum])
				}
				var loadimg = function(src){
					if(imgnum<imagegroup.length){
						
						
						
						/* 小程序开发思维的h5环境 */
						if(_this.ifwxapp == 0){
							uni.downloadFile({
								url:src.images,
								success:(res) => {
									imagegroup[imgnum].result = 1
									imagegroup[imgnum].imagedom = res.tempFilePath
									imgnum = imgnum + 1
									loadimg(imagegroup[imgnum])
								},
								fail:(err)=>{
									imagegroup[imgnum].result = 0
									errloadimg(imagegroup[imgnum])
								}
							})
							return;
						}
						
						
						
						/* 小程序开发思维的小程序和其他环境（原生小程序迁移只需迁移这部分） */
						if(src.images.indexOf('base64') == -1 && src.images.indexOf('data:') == -1 ){
							if(wx&&src.images.indexOf('http')==-1){
								wx.getFileSystemManager().readFile({
									filePath: src.images, // 选择图片返回的相对路径
									encoding: 'base64', // 编码格式
									success: res => { // 成功的回调
										imagegroup[imgnum].result = 1
										imagegroup[imgnum].imagedom = 'data:image/png;base64,' + uni.arrayBufferToBase64(uni.base64ToArrayBuffer(res.data))
										imgnum = imgnum + 1
										loadimg(imagegroup[imgnum])
									}
								})
							}else{
								uni.downloadFile({
									url:src.images,
									success:(res) => {
										imagegroup[imgnum].result = 1
										imagegroup[imgnum].imagedom = res.tempFilePath
										imgnum = imgnum + 1
										loadimg(imagegroup[imgnum])
									},
									fail:(err)=>{
										imagegroup[imgnum].result = 0
										errloadimg(imagegroup[imgnum])
									}
								})			
							}
						}else{
							imagegroup[imgnum].result = 1
							imagegroup[imgnum].imagedom = src.images
							imgnum = imgnum + 1
							loadimg(imagegroup[imgnum])
						}
						
						
						
					}else{
						checkcandrow()
					}
				}
				loadimg(imagegroup[imgnum])
			},
			//点击分享按钮触发绘制
			paintposter:function(){
				var obj = this.canvasobj || {imgs:require('../images/E5BLplaVoAQ3nl2.jpg'),title:'鄂温克发生过d325435sf上嘀咕嘀咕sdf345345士大夫大师傅dgdgffdgdfg35435','codelink':require('../images/code.jpg')}//同源,正常生成
				var objs = this.canvasobj || {imgs:'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png',title:'--','codelink':''}//跨域,生成失败
				this.fixshow = 1
				//调用canvas生成图片api
				setTimeout(() => {
					this.canvaspageWidth = 0
					this.canvaspageHeight = 0.1
					this.paintposterbase(480,800,[
						{
							type:'image',
							circle:0,//是否打开圆率,1为打开
							circler:3,//半径
							circler_deg:5,//圆角程度,越大越小
							circler_topleft:1,
							circler_topright:1,
							circler_bottomleft:1,
							circler_bottomright:1,
							images:obj.imgs,
							x:0,
							y:0,
							w:480,
							h:480,
							rotate:1,
							deg:0,
							result:0,
						},
						{
							type:'image',
							circle:1,//是否打开圆率,1为打开
							circler:140,//半径
							circler_deg:5,//圆角程度,越大越小
							circler_topleft:1,
							circler_topright:1,
							circler_bottomleft:1,
							circler_bottomright:1,
							images:obj.codelink,
							x:300,
							y:620,
							w:140,
							h:140,
							rotate:1,
							deg:0,
							result:0,
						},
						{
							type:'text',
							word:obj.title,//需要处理的文字
							fontSize: 36,//字体大小
							x: 20,//文字在x轴要显示的位置
							y: 490,//文字在y轴要显示的位置
							linechange:true,
							maxWidth: 440,//一行文字最大宽度
							maxLine: 2//文字最多显示的行数
						},
						{
							type:'text',
							word:'￥1.00',//需要处理的文字
							fontSize: 36,//字体大小
							x: 20,//文字在x轴要显示的位置
							y: 690,//文字在y轴要显示的位置
							linechange:false,
							maxWidth: 440,//一行文字最大宽度
							maxLine: 2//文字最多显示的行数
						},
					],(temp,success) => {
						if(temp&&success){
							this.postimgshowSrc = temp					
						}else{
							this.postimgshowSrc = temp	
							this.getpostersuccess = 0
						}
					})					
				})
			},
			getpostimg:function(){
				if(this.getpostersuccess){
					this.fixshow = 0
				}else{
					console.log('保存海报失败')
				}
			}
		}
	}
</script>

<style scoped>
	.hidden {
		height: 0 !important;
	}
	.fixed {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0,0,0,.7);
	}
	.fixedimgbox {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		padding-top: 90px;
		text-align: center;
	}
	.fixedimg {
		width: 240px;
		height: 400px;
		background-color: #eee;
	}
	.fixedbox {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 160px;
		background-color: white;
		transition: .3s;
	}
	.title {
		padding:10px 0;
		text-align: center;
		border-bottom: 1px solid #e0e0e0;
	}
	.navsbox {
		float: left;
		width: 25%;
		text-align: center;
		font-size: 14px;
	}
	.navsbox image {
		position: relative;
		display: block;
		margin: 20px auto 10px;
		width: 50px;
		height: 50px;
		background-color: #eee;
		border-radius: 50%;
		overflow: hidden;
	}
</style>
